'use strict';

const io = require('socket.io')();

//直接listen 使用polling模式？
io.listen(8003);

io.on('connection', function (socket) {
    console.log('connect');

    socket.on('disconnect', function () {
        console.log('disconnect');
    });

    socket.on('test', function (data) {
        console.log(data, typeof data);
    });

    socket.on('message', function (data) {
        console.log(data, typeof data);
    });

    socket.broadcast.emit('heheheheh');

});

//namespace
const ns = io.of('ns');
ns.on('connection', function (socket) {
    console.log('connect ns');

    socket.on('test', function (data) {
        console.log('ns', data, typeof data);
    });

    socket.on('disconnect', function () {
        console.log('disconnect ns');
    });
});

const ns1 = io.of('ns1');
ns1.on('connection', function (socket) {
    console.log('connect ns 1');

    socket.on('test', function (data) {
        console.log('ns1', data, typeof data);
    });

    socket.on('disconnect', function () {
        console.log('disconnect ns 1');
    });
});

const ns2 = io.of('ns2');
ns2.on('connection', function (socket) {
    console.log('connect ns 2');

    socket.on('test', function (data) {
        console.log('ns2', data, typeof data);
        socket.emit('receive', 'asdfasdfasdfa');
    });

    socket.on('disconnect', function () {
        console.log('disconnect ns 2');
    });
});

//room
const roomNS = io.of('roomNS');
roomNS.on('connection', function (socket) {
    console.log('connect room ns');

    socket.on('join', function (room) {
        socket.join(room);
        console.log('join room', room);

        roomNS.to('room1').emit('msg', room + ' socket join, namespace send msg to room, from "to room1"');
        roomNS.in('room2').emit('msg', room + ' socket join, namespace send msg to room, from "in room2"');//等价于to
        socket.to('room2').emit('msg', room + ' socket join, socket send msg to room, from "to room2"');//broadcasted的房间广播，不包括自身
    });

    socket.on('disconnect', function () {
        console.log('disconnect ns 2');
    });
});
